package com.yueqian.Service;


import com.yueqian.Dao.LoginMapper;
import org.apache.catalina.Session;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/LoginService")
public class LoginService extends HttpServlet {

    /**
     * 获取登录的请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         *  先获取用户信息
         */
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("userName");
        String password = req.getParameter("passWord");
        String code = req.getParameter("code");
        //获取验证码
        System.out.println("验证码："+code);
        //记住密码
        String remember = req.getParameter("remember");
        System.out.println("用户名："+username+"密码："+password);
        String  Verification_code = (String) req.getSession().getAttribute("CHECKCODE");
        if("".equals(code)){
            req.setAttribute("msg","验证码不能为空");
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }
        else {
            if (code.equalsIgnoreCase(Verification_code)) {
                System.out.println("验证码正确");
                /**
                 * 进行校验,减少对数据库的压力
                 */
                LoginMapper loginMapper = new LoginMapper(username, password);
                boolean result = loginMapper.login();
                if (result) {
                    System.out.println("登录成功");
                    if ("1".equals(remember)) {
                        //创建一个cookie去存储数据,传输前端
                        Cookie username1 = new Cookie("username", username);
                        Cookie password1 = new Cookie("password", password);
                        username1.setMaxAge(7 * 24 * 60 * 60); // 7天
                        password1.setMaxAge(7 * 24 * 60 * 60); // 7天
                        resp.addCookie(username1);
                        resp.addCookie(password1);
                        System.out.println("记住密码成功");
                    }
                    resp.sendRedirect("GetEmployee.jsp");
                } else {
                    System.out.println("登录失败");
                    resp.sendRedirect("fail.html");
                }

            } else {
                req.setAttribute("msg", "验证码错误");
                req.getRequestDispatcher("index.jsp").forward(req, resp);
                //重定向

            }
        }
         }
}
